package com.hailiang.ing;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SchoolServlet extends HttpServlet {
    ResultSet resultSet;
    PreparedStatement statement;
    Connection con;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer pid = Integer.valueOf(req.getParameter("pid"));
        resp.setContentType("application/json;charset=utf8");

        try {
          Class.forName("com.mysql.jdbc.Driver");
             con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo1?characterEncoding=utf8", "root", "root");
            statement = con.prepareStatement("select * from school where  pid=?");
            statement.setInt(1,pid);
             resultSet = statement.executeQuery();
            List<SchoolBean> sch = new ArrayList();
            while(resultSet.next()){
                SchoolBean schoolBean = new SchoolBean();
                schoolBean.setId(resultSet.getInt(1));
                schoolBean.setName(resultSet.getString(2));
                sch.add(schoolBean);
            }
            String json = JSON.toJSONString(sch);
            resp.getWriter().write(json);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                resultSet.close();
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
